<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>旅行社系统 - 跟团游订单</title>
    <!-- Bootstrap CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <!-- Bootstrap Icons -->
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.7.2/font/bootstrap-icons.css">
    <link rel="stylesheet" href="css/main.css">
    <!-- Vue.js -->
    <script src="https://cdn.jsdelivr.net/npm/vue@2.6.14"></script>
    <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
</head>
<body>
    <div id="app">
        <div class="container-fluid">
            <div class="row">
                <sidebar-nav 
                    current-page="package-orders"
                    @logout="handleLogout">
                </sidebar-nav>

                <!-- 主内容区 -->
                <main class="col-md-9 ms-sm-auto col-lg-10 px-md-4">
                    <div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3 border-bottom">
                        <h1 class="h2">跟团游订单管理</h1>
                        <div class="btn-toolbar mb-2 mb-md-0">
                            <button type="button" class="btn btn-primary" @click="showCreateModal">
                                <i class="bi bi-plus-circle"></i> 新增订单
                            </button>
                        </div>
                    </div>

                    <!-- 搜索栏 -->
                    <div class="row mb-3">
                        <div class="col-md-3">
                            <input type="text" class="form-control" v-model="searchQuery.order_number" placeholder="订单编号">
                        </div>
                        <div class="col-md-3">
                            <input type="text" class="form-control" v-model="searchQuery.customer_name" placeholder="客户姓名">
                        </div>
                        <div class="col-md-3">
                            <select class="form-select" v-model="searchQuery.status">
                                <option value="">所有状态</option>
                                <option value="draft">草稿</option>
                                <option value="confirmed">已确认</option>
                                <option value="paid">已支付</option>
                                <option value="completed">已完成</option>
                                <option value="cancelled">已取消</option>
                            </select>
                        </div>
                        <div class="col-md-3">
                            <button class="btn btn-primary" @click="searchOrders">
                                <i class="bi bi-search"></i> 搜索
                            </button>
                            <button class="btn btn-secondary ms-2" @click="resetSearch">
                                <i class="bi bi-x-circle"></i> 重置
                            </button>
                        </div>
                    </div>

                    <!-- 订单列表 -->
                    <div class="table-responsive">
                        <table class="table table-striped table-hover">
                            <thead>
                                <tr>
                                    <th>订单编号</th>
                                    <th>订单标题</th>
                                    <th>客户姓名</th>
                                    <th>总人数</th>
                                    <th>开始日期</th>
                                    <th>结束日期</th>
                                    <th>状态</th>
                                    <th>操作</th>
                                </tr>
                            </thead>
                            <tbody>
                                <tr v-if="orders.length === 0">
                                    <td colspan="8" class="text-center">暂无数据</td>
                                </tr>
                                <tr v-else v-for="order in orders" :key="order.ID">
                                    <td>{{ order.order_number }}</td>
                                    <td>{{ order.title }}</td>
                                    <td>{{ order.customer_name }}</td>
                                    <td>{{ order.total_people }}</td>
                                    <td>{{ formatDate(order.start_date) }}</td>
                                    <td>{{ formatDate(order.end_date) }}</td>
                                    <td>
                                        <span :class="getStatusBadgeClass(order.status)">
                                            {{ getStatusText(order.status) }}
                                        </span>
                                    </td>
                                    <td>
                                        <button class="btn btn-sm btn-outline-primary me-1" @click="showEditModal(order)">
                                            <i class="bi bi-pencil"></i>
                                        </button>
                                        <button class="btn btn-sm btn-outline-success me-1" @click="showPassengersModal(order)">
                                            <i class="bi bi-people"></i>
                                        </button>
                                        <button class="btn btn-sm btn-outline-secondary me-1" @click="showOrderDetail(order)">
                                            <i class="bi bi-info-circle"></i>
                                        </button>
                                        <button class="btn btn-sm btn-outline-danger" @click="handleDelete(order)">
                                            <i class="bi bi-trash"></i>
                                        </button>
                                    </td>
                                </tr>
                            </tbody>
                        </table>
                    </div>

                    <!-- 分页器 -->
                    <nav aria-label="Page navigation" class="mt-3">
                        <ul class="pagination justify-content-center">
                            <li class="page-item" :class="{ disabled: currentPage === 1 }">
                                <a class="page-link" href="#" @click.prevent="changePage(currentPage - 1)">上一页</a>
                            </li>
                            <li class="page-item" v-for="page in totalPages" :key="page"
                                :class="{ active: currentPage === page }">
                                <a class="page-link" href="#" @click.prevent="changePage(page)">{{ page }}</a>
                            </li>
                            <li class="page-item" :class="{ disabled: currentPage === totalPages }">
                                <a class="page-link" href="#" @click.prevent="changePage(currentPage + 1)">下一页</a>
                            </li>
                        </ul>
                    </nav>
                </main>
            </div>
        </div>

        <!-- 新增订单模态框 -->
        <div class="modal fade" id="createOrderModal" tabindex="-1" aria-labelledby="createOrderModalLabel" aria-hidden="true">
            <div class="modal-dialog modal-lg">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title">新增跟团游订单</h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                    </div>
                    <div class="modal-body">
                        <form @submit.prevent="handleSubmit">
                            <!-- 客户信息 -->
                            <div class="card mb-3">
                                <div class="card-header">
                                    <h6 class="mb-0">客户信息</h6>
                                </div>
                                <div class="card-body">
                                    <div class="d-flex align-items-center mb-3">
                                        <div v-if="selectedCustomer" class="flex-grow-1">
                                            <div class="border rounded p-2">
                                                <div><strong>{{ selectedCustomer.Name }}</strong> ({{ selectedCustomer.DisplayName }})</div>
                                                <div class="text-muted small">
                                                    电话: {{ selectedCustomer.PDFTelNo }} | 
                                                    邮箱: {{ selectedCustomer.PDFEmail }}
                                                </div>
                                            </div>
                                        </div>
                                        <div v-else class="flex-grow-1">
                                            <div class="border rounded p-2 text-muted">未选择客户</div>
                                        </div>
                                        <button type="button" class="btn btn-outline-primary ms-2" @click="showCustomerSelectModal">
                                            <i class="bi bi-person-plus"></i> 选择客户
                                        </button>
                                    </div>
                                </div>
                            </div>

                            <!-- 订单基本信息 -->
                            <div class="row mb-3">
                                <div class="col-md-12">
                                    <label class="form-label">订单标题</label>
                                    <input type="text" class="form-control" v-model="form.title" required>
                                </div>
                            </div>

                            <div class="row mb-3">
                                <div class="col-md-4">
                                    <label class="form-label">总人数</label>
                                    <input type="number" class="form-control" v-model.number="form.total_people" min="1" required>
                                </div>
                                <div class="col-md-4">
                                    <label class="form-label">开始日期</label>
                                    <input type="date" class="form-control" v-model="form.start_date" required>
                                </div>
                                <div class="col-md-4">
                                    <label class="form-label">结束日期</label>
                                    <input type="date" class="form-control" v-model="form.end_date" required>
                                </div>
                            </div>

                            <div class="row mb-3">
                                <div class="col-md-6">
                                    <label class="form-label">税率</label>
                                    <input type="number" class="form-control" v-model.number="form.tax_rate" min="0" max="1" step="0.01">
                                </div>
                            </div>

                            <div class="mb-3">
                                <label class="form-label">内部备注</label>
                                <textarea class="form-control" v-model="form.internal_notes" rows="2"></textarea>
                            </div>

                            <div class="mb-3">
                                <label class="form-label">客户备注</label>
                                <textarea class="form-control" v-model="form.customer_notes" rows="2"></textarea>
                            </div>

                            <div class="mb-3">
                                <label class="form-label">条款和条件</label>
                                <textarea class="form-control" v-model="form.terms_conditions" rows="3"></textarea>
                            </div>
                        </form>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                        <button type="button" class="btn btn-primary" @click="handleSubmit">保存</button>
                    </div>
                </div>
            </div>
        </div>

        <!-- 客户选择模态框 -->
        <div class="modal fade" id="customerSelectModal" tabindex="-1" aria-labelledby="customerSelectModalLabel" aria-hidden="true" style="z-index: 1060;">
            <div class="modal-dialog modal-lg">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title">选择客户</h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                    </div>
                    <div class="modal-body">
                        <!-- 客户搜索表单 -->
                        <form @submit.prevent="searchCustomers" class="mb-3">
                            <div class="row g-2">
                                <div class="col-md-4">
                                    <input type="text" class="form-control" v-model="customerSearch.name" placeholder="客户姓名">
                                </div>
                                <div class="col-md-4">
                                    <input type="text" class="form-control" v-model="customerSearch.customerNo" placeholder="客户编号">
                                </div>
                                <div class="col-md-4">
                                    <button type="submit" class="btn btn-primary me-2">搜索</button>
                                    <button type="button" class="btn btn-secondary" @click="resetCustomerSearch">重置</button>
                                </div>
                            </div>
                        </form>

                        <!-- 客户列表 -->
                        <div class="table-responsive">
                            <table class="table table-hover">
                                <thead>
                                    <tr>
                                        <th>客户编号</th>
                                        <th>姓名</th>
                                        <th>显示名称</th>
                                        <th>联系电话</th>
                                        <th>操作</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <tr v-for="customer in customers" :key="customer.ID">
                                        <td>{{ customer.LegacyCustomerNo }}</td>
                                        <td>{{ customer.Name }}</td>
                                        <td>{{ customer.DisplayName }}</td>
                                        <td>{{ customer.PDFTelNo }}</td>
                                        <td>
                                            <button type="button" class="btn btn-sm btn-success" @click="selectCustomer(customer)">
                                                选择
                                            </button>
                                        </td>
                                    </tr>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- 编辑订单模态框 -->
        <div class="modal fade" id="editOrderModal" tabindex="-1" aria-labelledby="editOrderModalLabel" aria-hidden="true">
            <div class="modal-dialog modal-lg">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title">编辑订单</h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                    </div>
                    <div class="modal-body">
                        <form @submit.prevent="handleUpdate">
                            <!-- 基本信息 -->
                            <div class="card mb-3">
                                <div class="card-header">
                                    <h6 class="mb-0">基本信息</h6>
                                </div>
                                <div class="card-body">
                                    <div class="row mb-3">
                                        <div class="col-md-6">
                                            <label class="form-label">订单编号</label>
                                            <input type="text" class="form-control" v-model="form.order_number" readonly>
                                        </div>
                                        <div class="col-md-6">
                                            <label class="form-label">状态</label>
                                            <select class="form-select" v-model="form.status">
                                                <option value="draft">草稿</option>
                                                <option value="confirmed">已确认</option>
                                                <option value="paid">已支付</option>
                                                <option value="completed">已完成</option>
                                                <option value="cancelled">已取消</option>
                                            </select>
                                        </div>
                                    </div>

                                    <div class="row mb-3">
                                        <div class="col-md-12">
                                            <label class="form-label">订单标题</label>
                                            <input type="text" class="form-control" v-model="form.title" required>
                                        </div>
                                    </div>

                                    <div class="row mb-3">
                                        <div class="col-md-4">
                                            <label class="form-label">总人数</label>
                                            <input type="number" class="form-control" v-model.number="form.total_people" min="1" required>
                                        </div>
                                        <div class="col-md-4">
                                            <label class="form-label">开始日期</label>
                                            <input type="date" class="form-control" v-model="form.start_date" required>
                                        </div>
                                        <div class="col-md-4">
                                            <label class="form-label">结束日期</label>
                                            <input type="date" class="form-control" v-model="form.end_date" required>
                                        </div>
                                    </div>
                                </div>
                            </div>

                            <!-- 客户信息 -->
                            <div class="card mb-3">
                                <div class="card-header">
                                    <h6 class="mb-0">客户信息</h6>
                                </div>
                                <div class="card-body">
                                    <div class="row mb-3">
                                        <div class="col-md-6">
                                            <label class="form-label">客户姓名</label>
                                            <input type="text" class="form-control" v-model="form.customer_name" required>
                                        </div>
                                        <div class="col-md-6">
                                            <label class="form-label">客户公司</label>
                                            <input type="text" class="form-control" v-model="form.customer_company">
                                        </div>
                                    </div>

                                    <div class="row mb-3">
                                        <div class="col-md-6">
                                            <label class="form-label">联系电话</label>
                                            <input type="tel" class="form-control" v-model="form.customer_phone" required>
                                        </div>
                                        <div class="col-md-6">
                                            <label class="form-label">电子邮箱</label>
                                            <input type="email" class="form-control" v-model="form.customer_email">
                                        </div>
                                    </div>
                                </div>
                            </div>

                            <!-- 费用信息 -->
                            <div class="card mb-3">
                                <div class="card-header">
                                    <h6 class="mb-0">费用信息</h6>
                                </div>
                                <div class="card-body">
                                    <div class="row mb-3">
                                        <div class="col-md-6">
                                            <label class="form-label">税率</label>
                                            <input type="number" class="form-control" v-model.number="form.tax_rate" min="0" max="1" step="0.01">
                                        </div>
                                        <div class="col-md-6">
                                            <label class="form-label">印花税金额</label>
                                            <input type="number" class="form-control" v-model.number="form.elevy_stamp_amount" min="0" step="0.01">
                                        </div>
                                    </div>
                                </div>
                            </div>

                            <!-- 备注信息 -->
                            <div class="card mb-3">
                                <div class="card-header">
                                    <h6 class="mb-0">备注信息</h6>
                                </div>
                                <div class="card-body">
                                    <div class="mb-3">
                                        <label class="form-label">内部备注</label>
                                        <textarea class="form-control" v-model="form.internal_notes" rows="2"></textarea>
                                    </div>

                                    <div class="mb-3">
                                        <label class="form-label">客户备注</label>
                                        <textarea class="form-control" v-model="form.customer_notes" rows="2"></textarea>
                                    </div>

                                    <div class="mb-3">
                                        <label class="form-label">条款和条件</label>
                                        <textarea class="form-control" v-model="form.terms_conditions" rows="3"></textarea>
                                    </div>
                                </div>
                            </div>
                        </form>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                        <button type="button" class="btn btn-primary" @click="handleUpdate">保存更新</button>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Bootstrap Bundle with Popper -->
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
    <script src="js/api/config.js"></script>
    <script src="js/api/auth.js"></script>
    <script src="js/components/Sidebar.js"></script>
    <script>
        new Vue({
            el: '#app',
            data: {
                orders: [],
                currentPage: 1,
                pageSize: 10,
                totalItems: 0,
                searchQuery: {
                    order_number: '',
                    customer_name: '',
                    status: ''
                },
                isLoading: false,
                form: {
                    title: '',               // 订单标题
                    total_people: 1,         // 总人数
                    start_date: '',          // 行程开始日期
                    end_date: '',           // 行程结束日期
                    customer_name: '',       // 客户姓名
                    customer_phone: '',      // 客户联系电话
                    customer_email: '',      // 客户联系邮箱
                    customer_company: '',    // 客户公司
                    tax_rate: 0.09,         // 税率
                    internal_notes: '',      // 内部备注
                    customer_notes: '',      // 给客户的备注
                    terms_conditions: '',    // 条款和条件
                    customer_profile_id: null // 客户ID
                },
                selectedCustomer: null,
                currentUser: null,
                createOrderModal: null,
                customerSelectModal: null,
                customerSearch: {
                    name: '',
                    customerNo: ''
                },
                customers: [],
                editOrderModal: null,
                currentEditingOrder: null,  // 当前正在编辑的订单
            },
            computed: {
                totalPages() {
                    return Math.ceil(this.totalItems / this.pageSize);
                }
            },
            created() {
                // 获取当前用户信息
                const userStr = localStorage.getItem(API_CONFIG.USER_KEY);
                if (userStr) {
                    this.currentUser = JSON.parse(userStr);
                }
                // 立即加载订单列表
                this.loadOrders();
            },
            mounted() {
                // 等待 DOM 更新后再初始化模态框
                this.$nextTick(() => {
                    const createOrderModalEl = document.getElementById('createOrderModal');
                    const customerSelectModalEl = document.getElementById('customerSelectModal');
                    
                    console.log('Modal elements:', {
                        createOrderModal: createOrderModalEl,
                        customerSelectModal: customerSelectModalEl
                    });

                    if (createOrderModalEl && customerSelectModalEl) {
                        try {
                            this.createOrderModal = new bootstrap.Modal(createOrderModalEl);
                            this.customerSelectModal = new bootstrap.Modal(customerSelectModalEl, {
                                backdrop: 'static'
                            });
                            console.log('Modals initialized successfully');
                        } catch (error) {
                            console.error('Error initializing modals:', error);
                        }
                    } else {
                        console.error('Modal elements not found', {
                            createOrderModalEl: !!createOrderModalEl,
                            customerSelectModalEl: !!customerSelectModalEl
                        });
                    }

                    const editOrderModalEl = document.getElementById('editOrderModal');
                    if (editOrderModalEl) {
                        this.editOrderModal = new bootstrap.Modal(editOrderModalEl);
                    }
                });
            },
            methods: {
                async loadOrders() {
                    try {
                        this.isLoading = true;
                        const response = await window.apiClient.get('/api/package-orders', {
                            params: {
                                ...this.searchQuery,
                                skip: (this.currentPage - 1) * this.pageSize,
                                limit: this.pageSize
                            }
                        });
                        
                        // 处理直接返回数组的情况
                        if (Array.isArray(response.data)) {
                            this.orders = response.data;
                            this.totalItems = response.data.length;
                        }
                        // 处理返回 {items, total} 格式的情况
                        else if (response.data && Array.isArray(response.data.items)) {
                            this.orders = response.data.items;
                            this.totalItems = response.data.total;
                        }
                        // 处理错误情况
                        else {
                            this.orders = [];
                            this.totalItems = 0;
                            console.error('Invalid response format:', response.data);
                        }
                    } catch (error) {
                        console.error('加载订单列表失败:', error);
                        this.orders = [];
                        this.totalItems = 0;
                        alert('加载订单列表失败');
                    } finally {
                        this.isLoading = false;
                    }
                },
                formatDate(date) {
                    return new Date(date).toLocaleDateString('zh-CN');
                },
                formatPrice(price) {
                    return price.toFixed(2);
                },
                getStatusBadgeClass(status) {
                    const classes = {
                        'draft': 'badge bg-secondary',
                        'confirmed': 'badge bg-success',
                        'paid': 'badge bg-info',
                        'completed': 'badge bg-primary',
                        'cancelled': 'badge bg-danger'
                    };
                    return classes[status] || 'badge bg-secondary';
                },
                getStatusText(status) {
                    const texts = {
                        'draft': '草稿',
                        'confirmed': '已确认',
                        'paid': '已支付',
                        'completed': '已完成',
                        'cancelled': '已取消'
                    };
                    return texts[status] || status;
                },
                async searchOrders() {
                    this.currentPage = 1;
                    await this.loadOrders();
                },
                resetSearch() {
                    this.searchQuery = {
                        order_number: '',
                        customer_name: '',
                        status: ''
                    };
                    this.searchOrders();
                },
                async changePage(page) {
                    if (page < 1 || page > this.totalPages) return;
                    this.currentPage = page;
                    await this.loadOrders();
                },
                showCreateModal() {
                    if (!this.createOrderModal) {
                        console.error('Create order modal not initialized');
                        return;
                    }
                    this.resetForm();
                    this.createOrderModal.show();
                },
                showEditModal(order) {
                    this.currentEditingOrder = order;
                    // 填充表单数据
                    this.form = {
                        order_number: order.order_number,
                        title: order.title,
                        total_people: order.total_people,
                        start_date: order.start_date.split('T')[0],
                        end_date: order.end_date.split('T')[0],
                        customer_name: order.customer_name,
                        customer_phone: order.customer_phone,
                        customer_email: order.customer_email,
                        customer_company: order.customer_company,
                        tax_rate: order.tax_rate,
                        elevy_stamp_amount: order.elevy_stamp_amount || 0,
                        status: order.status,
                        internal_notes: order.internal_notes,
                        customer_notes: order.customer_notes,
                        terms_conditions: order.terms_conditions,
                        customer_profile_id: order.customer_profile_id
                    };
                    
                    this.editOrderModal.show();
                },
                showDetailModal(order) {
                    // TODO: 实现查看订单详情功能
                },
                async handleCancel(order) {
                    if (!confirm('确定要取消这个订单吗？')) return;
                    try {
                        await window.apiClient.put(`/api/package-orders/${order.ID}/cancel`);
                        await this.loadOrders();
                    } catch (error) {
                        console.error('取消订单失败:', error);
                        alert('取消订单失败');
                    }
                },
                handleLogout() {
                    auth.logout();
                },
                async handleSubmit() {
                    try {
                        if (!this.selectedCustomer) {
                            alert('请先选择客户！');
                            return;
                        }

                        // 构建提交数据
                        const submitData = {
                            title: this.form.title,
                            total_people: this.form.total_people,
                            start_date: this.form.start_date + 'T00:00:00',  // 添加时间部分
                            end_date: this.form.end_date + 'T00:00:00',      // 添加时间部分
                            customer_name: this.form.customer_name,
                            customer_phone: this.form.customer_phone,
                            customer_email: this.form.customer_email,
                            customer_company: this.form.customer_company,
                            tax_rate: this.form.tax_rate,
                            internal_notes: this.form.internal_notes,
                            customer_notes: this.form.customer_notes,
                            terms_conditions: this.form.terms_conditions,
                            customer_profile_id: this.selectedCustomer.ID,
                            work_area_id: this.currentUser.workarea_id,
                            status: 'draft'  // 初始状态为草稿
                        };

                        await window.apiClient.post('/api/package-orders/', submitData);
                        this.createOrderModal.hide();
                        await this.loadOrders();
                        this.resetForm();
                        alert('订单创建成功！');
                    } catch (error) {
                        console.error('创建订单失败:', error);
                        alert(error.response?.data?.detail || '创建订单失败');
                    }
                },
                resetForm() {
                    this.form = {
                        title: '',
                        total_people: 1,
                        start_date: '',
                        end_date: '',
                        customer_name: '',
                        customer_phone: '',
                        customer_email: '',
                        customer_company: '',
                        tax_rate: 0.09,
                        internal_notes: '',
                        customer_notes: '',
                        terms_conditions: '',
                        customer_profile_id: null
                    };
                    this.selectedCustomer = null;
                },
                async searchCustomers() {
                    await this.loadCustomers();
                },
                resetCustomerSearch() {
                    this.customerSearch = {
                        name: '',
                        customerNo: ''
                    };
                    this.loadCustomers();
                },
                selectCustomer(customer) {
                    this.selectedCustomer = customer;
                    // 自动填充客户相关信息到表单
                    this.form.customer_name = customer.Name;
                    this.form.customer_phone = customer.PDFTelNo;
                    this.form.customer_email = customer.PDFEmail;
                    this.form.customer_company = customer.CompanyName;
                    this.form.customer_profile_id = customer.ID;
                    this.customerSelectModal.hide();
                },
                showCustomerSelectModal() {
                    this.loadCustomers();
                    this.customerSelectModal.show();
                },
                async loadCustomers() {
                    try {
                        const response = await window.apiClient.get('/api/customers', {
                            params: this.customerSearch
                        });
                        this.customers = Array.isArray(response.data) ? response.data : [];
                    } catch (error) {
                        console.error('加载客户列表失败:', error);
                        alert('加载客户列表失败');
                    }
                },
                async handleUpdate() {
                    try {
                        if (!this.currentEditingOrder) {
                            alert('未找到要编辑的订单！');
                            return;
                        }

                        const submitData = {
                            title: this.form.title,
                            total_people: this.form.total_people,
                            start_date: this.form.start_date + 'T00:00:00',
                            end_date: this.form.end_date + 'T00:00:00',
                            customer_name: this.form.customer_name,
                            customer_phone: this.form.customer_phone,
                            customer_email: this.form.customer_email,
                            customer_company: this.form.customer_company,
                            tax_rate: this.form.tax_rate,
                            elevy_stamp_amount: this.form.elevy_stamp_amount,
                            status: this.form.status,
                            internal_notes: this.form.internal_notes,
                            customer_notes: this.form.customer_notes,
                            terms_conditions: this.form.terms_conditions,
                            customer_profile_id: this.form.customer_profile_id,
                            work_area_id: this.currentUser.workarea_id
                        };

                        if (submitData.status === 'confirmed') {
                            submitData.confirmed_at = new Date().toISOString();
                        }

                        await window.apiClient.put(`/api/package-orders/${this.currentEditingOrder.ID}`, submitData);
                        this.editOrderModal.hide();
                        await this.loadOrders();
                        this.resetForm();
                        this.currentEditingOrder = null;
                        alert('订单更新成功！');
                    } catch (error) {
                        console.error('更新订单失败:', error);
                        alert(error.response?.data?.detail || '更新订单失败');
                    }
                },
                showOrderDetail(order) {
                    window.open(`package-order-detail.html?id=${order.ID}`, '_blank');
                }
            }
        });
    </script>
</body>
</html> 